// 云函数优化版
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 预定义类型映射表
const TYPE_COLLECTION_MAP = {
  food: 'FoodList',
  map: 'Pois',
  story: 'StoryList'
}

exports.main = async (event, context) => {
  const { action, poiId, poiData } = event
  const { OPENID: openid } = cloud.getWXContext()
  
  // 参数校验
   if (!TYPE_COLLECTION_MAP.hasOwnProperty(poiData.type)) {
    return { code: 400, msg: `无效类型: ${poiData.type}` }
  }

  // 获取对应集合名称
  const collectionType = TYPE_COLLECTION_MAP[poiData.type]

  // 事务操作
  return db.runTransaction(async transaction => {
    // 1. 更新主数据状态
    const updateResult = await transaction.collection(collectionType)
      .doc(poiId)
      .update({
        data: { islike: action === 'follow' }
      })

    if (updateResult.stUpdated === 0) {
      throw new Error('数据更新失败')
    }

    // 2. 处理收藏记录
    const collectionQuery = {
      poiId,
      userId: openid,
      type: poiData.type
    }

    // 查询现有记录
    const { data } = await transaction.collection('CollectList')
      .where(collectionQuery)
      .field({ _id: 1 })
      .get()

    // 操作处理
    if (action === 'follow') {
      if (data.length > 0) {
        throw new Error('操作冲突：已存在收藏记录')
      }
      await transaction.collection('CollectList').add({
        data: {
          ...collectionQuery,
          ...poiData,
          createTime: db.serverDate()
        }
      })
    } else {
      if (data.length > 0) {
        await transaction.collection('CollectList')
          .doc(data[0]._id)
          .remove()
      }
    }

    return { code: 0 }
  }).catch(err => {
    console.error('事务失败:', err)
    return {
      code: /操作冲突/.test(err.message) ? 409 : 500,
      msg: err.message.replace('transaction failed: ', '')
    }
  })
}